mysql = require 'mysql'
_ = require 'underscore'

config = require '../config/config'
logger = require '../libs/logger'
util = require '../libs/util'
Q = require 'q'
async = require 'async'

class logmsg
  constructor: (options)->
    @options = options

  addNewLogs: (options, cb)->  #支持多个收信人
    if options.user_type == 2
      _accountIds = JSON.parse(options.account_ids)  #parse string to json
      _data = {}
      _data.send_success = []
      _data.send_fail = []
      _sendMsgTaskProcess = (_accountId, callback)->
        sql = "insert into zy_message set create_time=unix_timestamp(now()),m_type='sys_manager_msg',account_id=?,?"
        data = _.pick(options, 'title','content','object_id','sender') #get selected values
        util.queryDatabase sql, [_accountId,data], (err, result)->
          if err
            logger.error 'new logs error:', err
            callback {err: 1, Code: err.Code ? 'Zy.InternalError'}
          else
            _data.send_success.push {account: _accountId,id: result['insertId']}
            callback null

      Q
      .fcall(()->
        sql = "select a.* from zy_account a left join zy_customer_account b on a.account=b.ca_account_id where a.account in (?) and b.ca_customer_id=?"
        return Q.nfcall util.queryDatabase, sql, [_accountIds, options.customer_id]
      )
      .then((result)->
        _availableAccountIds = _.map result, (item)->
          return item.account
        _data.send_fail = _.filter _accountIds,(item)->
          return not _.contains(_availableAccountIds, item)

        qq = async.queue(_sendMsgTaskProcess, 1)
        qq.push(_availableAccountIds, (err)->
          logger.error 'some err:', JSON.stringify(err) if err
        )
        qq.drain = ()->
          cb {err: 0,data: _data}
      )
    else
      _accountIds = JSON.parse(options.account_ids)
      _data = {}
      _data.send_success = []
      _data.send_fail = []
      _sendMsgTaskProcess = (_accountId, callback)->
        sql = "insert into zy_message set create_time=unix_timestamp(now()),m_type='sys_manager_msg',account_id=?,?"
        data = _.pick(options, 'title','content','object_id','sender')
        util.queryDatabase sql, [_accountId,data], (err, result)->
          if err
            logger.error 'new logs error:', err
            callback {err: 1, Code: err.Code ? 'Zy.InternalError'}
          else
            _data.send_success.push {account: _accountId,id: result['insertId']}
            callback null

      Q
      .fcall(()->
        sql = "select * from zy_account where account in (?)"
        return Q.nfcall util.queryDatabase, sql, [_accountIds]
      )
      .then((result)->
        _availableAccountIds = _.map result, (item)->
          return item.account
        _data.send_fail = _.filter _accountIds,(item)->
          return not _.contains(_availableAccountIds, item)

        qq = async.queue(_sendMsgTaskProcess, 1)
        qq.push(_availableAccountIds, (err)->
          logger.error 'some err:', JSON.stringify(err) if err
        )
        qq.drain = ()->
          cb {err: 0,data: _data}
      )

  getSendLogsOfSelf: (options, cb)->
    Q
    .fcall(()->
      _data = []
      sql = "select a.*,b.`name` as user_name,b.user_type,b.tel,b.`status` as user_status,b.org_id, b.org_name,d.`id` as agent_id,d.agent_name from zy_message a
             inner join zy_account b on a.account_id=b.account
             left join zy_agent d on b.agent_id=d.id
             where a.sender=?"

      _data.push options.sender
      if options.m_status
        sql += " and a.status in (?)"
        _data.push JSON.parse(options.m_status)
      if options.m_type
        sql += " and a.m_type in (?)"
        _data.push JSON.parse(options.m_type)
      if options.accept_account_id
        sql += " and a.account_id=?"
        _data.push options.accept_account_id
      if options.status
        sql += " and b.status in (?)"
        _data.push JSON.parse(options.status)
      if options.org_id
        sql += " and c.id=?"
        _data.push options.org_id

      if options.agent_id
        sql += ' and d.id=?'
        _data.push options.agent_id

      if options.field == 'user_type_name' and options.text
        sql += " and d.name like ?"
        _data.push "%#{options.text}%"
      else if options.field == 'org_name' and options.text
        sql += " and c.name like ?"
        _data.push "%#{options.text}%"
      else if options.field == 'accept_account_id' and options.text
        sql += " and a.account_id like ?"
        _data.push "%#{options.text}%"
      else if options.field == 'title' and options.text
        sql += " and a.title like ?"
        _data.push "%#{options.text}%"
      else if options.field == 'content' and options.text
        sql += " and a.content like ?"
        _data.push "%#{options.text}%"

      pageIndex = (+options.pageIndex - 1) or 0
      pageSize = (+options.pageSize) or config.getPageSize()
      startIndex = (pageIndex * pageSize)
      sql += " order by create_time DESC LIMIT #{startIndex}, #{pageSize}"

      return Q.nfcall util.queryDatabaseByPage, sql, _data
    )
    .then((result)->
      data =
        Total: result['total']
        Data: result.data
      cb {err: 0, data: data}
    )
    .fail((err)->
      logger.error 'get message failed:', err
      cb {err: 4, Code: err.Code ? 'Zy.InternalError'}
    )

  listLogs: (options, cb)->
    sql = "select SQL_CALC_FOUND_ROWS * from zy_log where 1=1"
    if options.field and options.text
      sql += " and #{mysql.escapeId(options.field)} like #{mysql.escape('%' + options.text + '%')}"
    if options.operate
      sql += " and `operate`=#{mysql.escape(options.operate)}"
    if options.time_begin
      sql += " and `create_time`>=#{+options.time_begin}"
    if options.time_end
      sql += " and `create_time`<=#{+options.time_end + 24 * 3600 - 1}"

    pageIndex = (+options.pageIndex - 1) or 0
    pageSize = (+options.pageSize) or config.getPageSize()
    startIndex = (pageIndex * pageSize)
    sql += " order by create_time DESC LIMIT #{startIndex}, #{pageSize}"


    util.queryDatabaseByPage(sql, '', (err, result)->
      if not err
        data =
          Total: result['total']
          Data: result.data
        cb {err: 0, data: data}
      else
        logger.error "list log data error::#{err.toString()}"
        cb {err: 4, Code: err.Code ? 'Zy.InternalError'}
    )

  listLogsForCustomer: (options, cb)->
    sql = "select SQL_CALC_FOUND_ROWS * from zy_log a inner join zy_customer_account b on
           a.account_id=b.ca_account_id where b.ca_customer_id=#{mysql.escape(options.customer_id)} "
    if options.field and options.text
      sql += " and #{mysql.escapeId(options.field)} like #{mysql.escape('%' + options.text + '%')}"
    if options.operate
      sql += " and `operate`=#{mysql.escape(options.operate)}"
    if options.time_begin
      sql += " and `create_time`>=#{+options.time_begin}"
    if options.time_end
      sql += " and `create_time`<=#{+options.time_end + 24 * 3600 - 1}"

    pageIndex = (+options.pageIndex - 1) or 0
    pageSize = (+options.pageSize) or config.getPageSize()
    startIndex = (pageIndex * pageSize)
    sql += " order by create_time DESC LIMIT #{startIndex}, #{pageSize}"


    util.queryDatabaseByPage(sql, '', (err, result)->
      if not err
        data =
          Total: result['total']
          Data: result.data
        cb {err: 0, data: data}
      else
        logger.error "list log data error::#{err.toString()}"
        cb {err: 4, Code: err.Code ? 'Zy.InternalError'}
    )

  listMsg: (options, cb)->
    sql = "select SQL_CALC_FOUND_ROWS * from zy_message where account_id=?"
    if options.field and options.text
      sql += " and #{mysql.escapeId(options.field)} like #{mysql.escape('%' + options.text + '%')}"

    if options.status
      sql += " and `status`=#{mysql.escape(options.status)}"

    if options.time_begin
      sql += " and a.create_time>=#{+options.time_begin}"

    if options.time_end
      sql += " and a.create_time<=#{+options.time_end}"

    pageIndex = (+options.pageIndex - 1) or 0
    pageSize = (+options.pageSize) or config.getPageSize()
    startIndex = (pageIndex * pageSize)
    sql += " order by create_time DESC LIMIT #{startIndex}, #{pageSize}"

    util.queryDatabaseByPage(sql, options.account_id, (err, result)->
      if not err
        _d = result.data
        try
          _d = _.map result.data, (item)->
            item['content'] = util.gettext(item['content'], options.lang)
            return item
        catch ex
        data =
          Total: result['total']
          Data: _d
        cb {err: 0, data: data}
      else
        logger.error "list msg data error::#{err.toString()}"
        cb {err: 4, Code: err.Code ? 'Zy.InternalError'}
    )


#设置消息为已读
  setUnreadMsg: (options, cb)->
    try
      ids = JSON.parse options.ids
    catch
      ids = ['']
    sql = "update zy_message set `status`=1 where account_id=? and `id` in (?)"
    util.queryDatabase(sql, [options.account_id, ids], (err, results) ->
      if not err
        cb {err: 0}
      else
        cb {err: 4, Code: err.Code ? 'Zy.InternalError'}
        logger.error "update log status error::#{err.toString()}"
    );

module.exports = logmsg